package com.spark.tags;

import java.util.Map;

import com.spark.core.SparkBuilder;
import com.spark.core.SparkContext;
import com.spark.core.XMap;

@SuppressWarnings("unchecked")
public class GridNavBar extends ViewComponent {
	
	public static final String TAG_NAME = "gridNavBar";
	
	private static final String BTN_ICON_CLS_PREPAGE = "s-nav-pre";
	private static final String BTN_ICON_CLS_REFRESH = "s-nav-refresh";
	private static final String BTN_ICON_CLS_NEXTPAGE = "s-nav-next";
	
	private static final String PROPERTITY_NAV_BUTTONS = "navButtons";	
	private static final String DEFAULT_TEMPLATES = "gridNavBar.ftl";
	private static final String DEFAULT_CLASSNAME = "s-nav";	
	
	protected int getDefaultHeight(){
		return 26;
	}
	
	public String getTemplate() {
		return DEFAULT_TEMPLATES;
	}
	
	protected String getDefaultClass(XMap view,SparkContext context){
		return DEFAULT_CLASSNAME;
	}
	
	public void init(XMap view, SparkContext context) throws Exception {
		super.init(view, context);
		String ds = view.getString(PROPERTITY_BIND);
		context.addJsonConfig(PROPERTITY_BIND, ds);
		
		
		XMap groupButton = new XMap(GroupButton.TAG_NAME);
		groupButton.setNameSpaceURI(DEFAULT_NAME_SPACE);
		
		StringBuffer sb = new StringBuffer();
		sb.append("function(){$('").append(ds).append("').prePage()}");
		groupButton.addChild(createButton(BTN_ICON_CLS_PREPAGE,sb.toString(),"上一页"));
		sb = new StringBuffer();
		sb.append("function(){$('").append(ds).append("').refresh()}");
		groupButton.addChild(createButton(BTN_ICON_CLS_REFRESH,sb.toString(),"刷新"));
		sb = new StringBuffer();
		sb.append("function(){$('").append(ds).append("').nextPage()}");
		groupButton.addChild(createButton(BTN_ICON_CLS_NEXTPAGE,sb.toString(),"下一页"));
		context.put(PROPERTITY_NAV_BUTTONS, SparkBuilder.build(groupButton, context));
	}
	
	
	private XMap createButton(String iconCls,String function, String tooltip){
		XMap button = new XMap(Button.TAG_NAME);
		button.setNameSpaceURI(DEFAULT_NAME_SPACE);
		button.put(Button.PROPERTITY_ICON_CLASS, iconCls);
		button.put(Button.PROPERTITY_TOOLTIP, tooltip);
		button.put(PROPERTITY_WIDTH, new Integer(35));
		if(!"".equals(function))button.put(Button.PROPERTITY_CLICK, function);
		return button;
	}
	
	
	protected String build(SparkContext context){
		Map map = context.getMap();
		StringBuilder sb = new StringBuilder();
		sb.append("<div class=\"").append(get(map,"className")).append("\" id=\"").append(get(map,"id")).append("\" style=\"").append(get(map,"style")).append("\"><div class=\"info\">&nbsp;</div>").append(get(map,"navButtons")).append("</div>");
		sb.append("<script>new Spark.GridNavBar(").append(get(map,"config")).append(");</script>");
		return sb.toString();
	}
	
}
